/**
 * Created by apple on 16/7/14.
 */
angular.module('starter.spmsCacheService',['ionic'])
  .service('$dfCache', function ($timeout,$log,ENV,$q, $dfHttp,$dfDB) {
    var obj ;
    var collection ;
    //
    return {
      //projectId
      //手机缓存 文件(realm) 图片,配置(keystore,cer),资源,zip,tar.gz(增量更新,插件化,不打包部署)
      // sqlite(coreData,realm) 结构化数据(微信朋友圈,微博的列表(查询),数据需要处理删除和修改),
      // userDefaults(用户数据,简单的key—value)

      putObject: function (key, object) {
        console.log('cacheCollection.putObject is',obj);
        if (!obj) {
          collection = $dfDB.collectionDBSync('cacheCollection');

          var objArray = collection.find({'cacheObj': 'cacheObj'});
          if (objArray.length == 0) {
            obj = {'cacheObj': 'cacheObj', 'cache': {}};
            collection.insert(obj);
            $dfDB.dbSave();

            var objectArray = collection.find({'cacheObj': 'cacheObj'});
            if(objectArray && objectArray.length > 0) {
              obj = objectArray[0];
            }

          } else {
            obj = objArray[0];
          }
        }

        if (!obj.cache) {
          obj.cahce = {};
        }

        ////如果key不是String 报错
        //if (Object.prototype.toString.call(key) !== '[object String]') {
        //  throw new Error('userDefault`s key must be string ,current is ' + Object.prototype.toString.call(key));
        //} else if (Object.prototype.toString.call(object) === '[object Undefined]' || Object.prototype.toString.call(object) === '[object Null]') {
        //  //如果key值是undefined 或者是null 则直接删除该属性(设置为undefined)
        //  obj.cache['' + key + ''] = undefined;
        //} else if (Object.prototype.toString.call(object) === '[object Array]') {
        //  obj.cache['' + key + ''] = JSON.stringify(object);
        //} else if (Object.prototype.toString.call(object) === '[object Object]') {
        //  obj.cache['' + key + ''] = JSON.stringify(object);
        //} else if (Object.prototype.toString.call(object) === '[object String]') {
        //  obj.cache['' + key + ''] = object;
        //}

        obj.cache['' + key + ''] = object;
        collection.update(obj);
        $dfDB.dbSave();

        var objArray = collection.find({'cacheObj': 'cacheObj'});
        if(objArray && objArray.length > 0) {
          obj = objArray[0];
        }

      },
      getObject:function(key){
        if(!obj) {
          collection = $dfDB.collectionDBSync('cacheCollection');
          var objArray = collection.find({'cacheObj': 'cacheObj'});
          if (objArray.length == 0) {
            obj = {'cacheObj':'cacheObj','cache':{}};
            collection.insert(obj);
            $dfDB.dbSave();

            var objectArray = collection.find({'cacheObj': 'cacheObj'});
            if(objectArray && objectArray.length > 0) {
              obj = objectArray[0];
            }
          } else {
            obj = objArray[0];
          }
        }
        console.log('cacheCollection.getObject is',obj);
        if(!obj.cache){
          obj.cache = {};
        }

        if(obj.cache.hasOwnProperty(''+key+'')){
          return obj.cache[''+key+''];
        }else {
          return {};
        }

      }
    }
  })

  .service('$region',function($dfDB,$dfHttp,$timeout){

    var collection ;

    function get() {
      if (!collection) {
        collection = $dfDB.collectionRegionDBSync('reginCollection');
      }
      var array = collection.find({code:'ALL'});
      if(array.length > 0){
        return array[0];
      }
      return {code:'ALL',data:[]};
    }

    function dfHttpGet() {
      $dfHttp.get('api/others/getAllRegionList.json').success(function(data){
        if(data.code == 'SUCCESS'){
          save(data.data);
        }
      }).error(function(data){

      })
    }

    $timeout(function(){
      if(get().data.length == 0){
        dfHttpGet();
      }
    },2000);

    function save(obj){
      //TODO:
      if (!collection) {
        collection = $dfDB.collectionRegionDBSync('reginCollection');
      }
      collection.removeWhere({});

      if (angular.isArray(obj)) {
        angular.forEach(obj,function(province){
          //console.log(province);
          if(angular.isArray(province.cityList)){
            angular.forEach(province.cityList,function(city){
              //console.log(city);
              if(angular.isArray(city.regionList)){
                angular.forEach(city.regionList,function(region){
                  //console.log(region);
                  var regionDB = {};
                  regionDB.provinceCode = province.provinceCode ;
                  regionDB.provinceName = province.provinceName ;
                  regionDB.cityCode = city.cityCode ;
                  regionDB.cityName = city.cityName ;
                  regionDB.regionCode = region.regionCode ;
                  regionDB.regionName = region.regionName ;
                  collection.insert(regionDB);
                })
              }
            })
          }
        });
        collection.insert({code:'ALL',data:obj});
        $dfDB.dbSave();
      }
    }

    function getWithRegion(regionCode) {
      if (!collection) {
        collection = $dfDB.collectionRegionDBSync('reginCollection');
      }
      var region = collection.find({'regionCode':regionCode});
      if(region.length > 0) {
        return region[0] ;
      } else {
        return {};
      }
    }

    return {
      save:save,
      get:get,
      dfHttpGet:dfHttpGet,
      getWithRegion:getWithRegion
    }
  })

  .service('$design',function($dfDB,$dfHttp,$timeout){

    function dfHttpGet() {
      $dfHttp.get('api/others/getAllItem.json').success(function(data){
        if(data.code == 'SUCCESS'){
          save(data.data);
        }
      }).error(function(data){

      })
    }

    var collection ;

    $timeout(function(){
      dfHttpGet()
    },1000);

    function save(obj){
      if (!collection) {
        collection = $dfDB.collectionDBSync('designCollection');
      }
      collection.removeWhere({});

      if (angular.isArray(obj)) {
        angular.forEach(obj,function(item){

          //console.log(region);
          var designDB = {};
          designDB.itemCode = item.itemCode;
          designDB.itemName = item.itemName;
          designDB.itemDesc = item.itemDesc;
          designDB.category1 = item.category1;
          designDB.category2 = item.category2;
          designDB.xd = item.xd;
          designDB.dbw = item.dbw;
          designDB.ddgl = item.ddgl;
          designDB.imgUrl = item.imgUrl;
          designDB.zjrl = item.zjrl;
          designDB.zjsl = item.zjsl;
          designDB.edgl = item.edgl;
          designDB.itemLength = item.itemLength;
          designDB.property10 = item.property10;
          designDB.property11 = item.property11;
          designDB.property12 = item.property12;
          designDB.property13 = item.property13;
          designDB.categoryCode = item.categoryCode;
          designDB.type = item.type;
          designDB.specs = item.specs;
          designDB.material = item.material;

          collection.insert(designDB);

        });
        $dfDB.dbSave();
      }
    }

    function getWithProperty(properties) {
      if (!collection) {
        collection = $dfDB.collectionDBSync('designCollection');
      }
      var design = collection.find(properties);
      if(design.length > 0) {
        return design;
      } else {
        return {};
      }
    }

    return {
      save:save,
      dfHttpGet:dfHttpGet,
      getWithProperty:getWithProperty
    }
  })

  .service('$supplier',function($dfDB,$dfHttp,$timeout){

    var collection ;

    function dfHttpGet() {
      $dfHttp.get('api/others/getAllProviderList.json?userId=58&lastUpdateDate=1970-01-01 01:01:01').success(function(data){
        if(data.code == 'SUCCESS'){
          save(data.data);
        }
      }).error(function(data){

      })
    }

    $timeout(function(){
      dfHttpGet();
    },1000);

    function save(obj){
      if (!collection) {
        collection = $dfDB.collectionDBSync('supplierCollection');
      }
      collection.removeWhere({});

      if (angular.isArray(obj)) {
        angular.forEach(obj,function(item){

          //console.log(region);
          var supplierDB = {};
          supplierDB.contacts = item.contacts;
          supplierDB.contactsTel = item.contactsTel;
          supplierDB.distributorFlag = item.distributorFlag;
          supplierDB.installerFlag = item.installerFlag;
          supplierDB.providerAddress = item.providerAddress;
          if(angular.isArray(item.providerAddress)){
            supplierDB.providerAddress = JSON.stringify(item.providerAddress) ;
          }
          supplierDB.providerCode = item.providerCode;
          supplierDB.providerName = item.providerName;

          collection.insert(supplierDB);

        });
        $dfDB.dbSave();
      }
    }

    function getWithProperty(properties) {
      if (!collection) {
        collection = $dfDB.collectionDBSync('supplierCollection');
      }
      var suppliers = collection.find(properties);
      if(suppliers.length > 0) {
        angular.forEach(suppliers,function (supplier) {
          if(angular.isString(supplier.providerAddress)){
            supplier.providerAddress = JSON.parse(supplier.providerAddress);
          }
        });
        return suppliers;
      } else {
        return {};
      }
    }

    return {
      save:save,
      dfHttpGet:dfHttpGet,
      getWithProperty:getWithProperty
    }
  })

  .service('$imageUploadCache',function($dfDB,$dfHttp,$timeout){
    var collection ;

    function saveImages(params){
      if(!params.funId || !params.funName || !params.imageClass) {
        throw new Error('params must has funId ,funName ,imageClass');
        return ;
      }
      if(!collection){
        collection = $dfDB.collectionDBSync('imageUploadCache');
      }
      var imageCaches = collection.find({'$and':[{'funId':params.funId},{'funName':params.funName},{'imageClass':params.imageClass}]});

      if(imageCaches.length > 0) {
        angular.forEach(imageCaches,function(imageCache){
          imageCache.images = params.images ;
          imageCache.invalidUuids = params.invalidUuids ;
          imageCache.imageStatus = params.imageStatus ;
          collection.update(imageCache);
        })
      }else {
        collection.insert(params);
      }
      $dfDB.dbSave();
    }

    function getImagesByParams(funId,funName,imageClass){

      if(!collection){
        collection = $dfDB.collectionDBSync('imageUploadCache');
      }

      // var imageCaches = collection.find({funId:funId,funName:funName,imageClass:imageClass});

      var imageCaches = collection.find({'$and':[{'funId':funId},{'funName':funName},{'imageClass':imageClass}]})

      if(imageCaches.length > 0){
        return imageCaches[0];
      }else {
        return {};
      }
    }

    function  getImageWithStatus(status){
      if(!collection){
        collection = $dfDB.collectionDBSync('imageUploadCache');
      }
      var imageCaches = collection.find({'$and':[{'imageStatus':status}]});

      return imageCaches ;
    }

    function getImagesCount(funId,funName,imageClass) {
      if(!collection){
        collection = $dfDB.collectionDBSync('imageUploadCache');
      }

      var imageCaches = collection.find({'$and':[{'funId':funId},{'funName':funName},{'imageClass':imageClass}]});

      if(imageCaches.length > 0){
        if(angular.isArray(imageCaches[0].images)){
          return imageCaches[0].images.length;
        }else{
          return 0;
        }
      }else {
        return 0;
      }
    }

    return {
      saveImages:saveImages,
      getImagesByParams:getImagesByParams,
      getImagesCount:getImagesCount,
      getImageWithStatus:getImageWithStatus
    }

  })
